// pages/my/personalData/bindingMobile/index.js
var verification = require("../../../../utils/util.js");
Page({

  /**
   * 页面的初始数据
   */
  data: {
    mobile: '', // 手机号
    code: '',   // 验证码
    codeStatus: false,
    time: 60000, // 倒计时

    userVerifyKey: '', // 密钥
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    let mobile = wx.getStorageSync('token');
    this.setData({ mobile })
    console.log(mobile)
  },
  // 修改手机号
  modifyPhone(e){
    let mobile = this.data.mobile               // 手机号
    let code = this.data.code                   // 验证码
    let userVerifyKey = this.data.userVerifyKey // 密钥
    if(verification.isPhoneNumber(mobile)){
      if(code.length == 6){
        var pages = getCurrentPages();//当前页面栈
        var prevPage = pages[pages.length - 2];//获取上一个页面实例对象
        prevPage.setData({
          mobile,
          code,
          userVerifyKey,
        })
        prevPage.bindingMobile(); // 触发绑定手机
        wx.navigateBack({
          delta: 1
        })
      }else{
        wx.showToast({ icon: 'none',title: '请完善验证码'});
      }
    }else{
      wx.showToast({ icon: 'none',title: '手机号有误'});
    }
  },
  // 获取验证码
  onVerificationCode(){
    let mobile = this.data.mobile
    let that = this
    if(verification.isPhoneNumber(mobile)){
      wx.cloud.init()
      wx.cloud.callContainer({
        config: {
          env: 'prod-0g38oh8hf0e4d5ac', 
        },
        path: '/v1/user/initVerify', 
        method: 'POST',
        header: {
          'X-WX-SERVICE': 'springboot-069k', 
        },
        data: {
          mobile,
        }
      }).then(res => {
        if(res.data.code == 1){
          let { userVerifyKey } = res.data.data
          that.setData({ codeStatus: true,userVerifyKey })
        }else{
          wx.showToast({ icon: 'none',title: res.data.errorMsg });
          
        }
      })
    }else{
      wx.showToast({ icon: 'none',title: '手机号有误'});
    }
  },
  // 验证码倒计时后执行
  finished () {
    this.setData({ codeStatus: false })
  },
})